//Page Object
import { allChannels,getArticles } from "../../api/news"
Page({
  data: {
    active: 0,
    allChannelsList:[],
    refresher:"",
    articlesList:[],
    pre_timestamp:null,
    channelId:0,
    flag:false,
    show:true,
    show1:false
  },
  goDetail(e) {
    // console.log(e);
    wx.navigateTo({
      url:'/pages/detail/detail?id=' + e.currentTarget.id
    })
  },
  channel() {
    this.setData({
      show1:true
    })
  },
  onClose() {
    this.setData({
      show1:false
    })
  },
  goSearch() {
    wx.navigateTo({
      url: '/pages/search/search'
    });
  },
  async getarticlesList() {
    try {
      const res = await getArticles({
        channel_id:this.data.channelId,
        timestamp: +new Date(),
        with_top:1
      })
      // console.log(res);
      this.setData({
        articlesList:res.data.results,
        pre_timestamp:res.data.pre_timestamp,
      })
    } catch (error) {
      this.setData({
        refresher:"请求失败，点击重新加载"
      })
    }
    // console.log(res.data.results);
  },

  onChange(event) {
    // console.log(event);
    this.setData({
      channelId:event.detail.name
    })
    this.getarticlesList()
    // wx.showToast({
    //   title: `切换到标签 ${event.detail.name}`,
    //   icon: 'none',
    // });
  },
  bindrefresherpulling(e) {
    // console.log(e);
    if(e.detail.dy>45) {
      this.setData({
        refresher:'释放即可刷新...'
      })
    } else {
      this.setData({
        refresher:'下拉即可刷新...'
      })
    }
  },
  async bindscrolltolower() {
    const res = await getArticles({
      channel_id:this.data.channelId,
      timestamp: this.data.pre_timestamp,
      with_top:1
    })
    console.log(res);
    this.setData({
      articlesList:[...this.data.articlesList,...res.data.results],
      pre_timestamp:res.data.pre_timestamp,
    })
  },
  async bindrefresherrefresh() {
    this.setData({
      refresher:'加载中...'
    })
    try {
      await this.getarticlesList()
      this.setData({
        refresher:'刷新成功',
      })
    } catch (error) {
      this.setData({
        refresher:'刷新失败，稍后重试',
      })
    }
    setTimeout(() => {
     this.setData({
      flag:false
     })
    },2000)
  },
  //options(Object)
  onLoad: async function(options){
    const res = await allChannels()
    // console.log(res);
    this.setData({
      allChannelsList:res.data.channels
    })
    this.selectComponent('#tabs').resize();
    this.getarticlesList()
  },
  onReady: function(){
    
  },
  onShow: function(){
    
  },
  onHide: function(){

  },
  onUnload: function(){

  },
  onPullDownRefresh: function(){
  },
  onReachBottom: function(){
  },
  onShareAppMessage: function(){

  },
  onPageScroll: function(){

  },
  //item(index,pagePath,text)
  onTabItemTap:function(item){

  }
});